from django.shortcuts import render

from shopping.models import Cart,Goods,User
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import viewsets
import logging
logging = logging.getLogger('django')

from shopping.serializers import CartSerializer,GoodsSerializer,UserSerializer
from rest_framework.permissions import IsAuthenticated
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate

# Create your views here.
class GoodsViewSet(viewsets.ModelViewSet):
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer



# 添加购物车
class CartAddView(APIView):

    permission_classes = [IsAuthenticated]
    def post(self,request):
        try:
            user_id = request.user.id
            # 接收参数：课程id和课程添加数量
            goods_id = request.data.get('goods_id')
            quantity = int(request.data.get('quantity',1))

            if not goods_id:
                logging.error('请传递你要添加的课程')
                return Response({
                    'code':0,
                    'message':'请传递你要添加的课程'
                })

            # 检查是否已在购物车中
            try:
                cate_goods = Cart.objects.get(user_id=user_id,goods_id=goods_id)
                if cate_goods:
                    cate_goods.quantity += quantity
                    cate_goods.save()
                    return Response({
                        'code':1,
                        'message':'添加成功',
                        'data':CartSerializer(cate_goods).data
                    })
            except Cart.DoesNotExist:
                new_goods = Cart.objects.create(
                    user_id=user_id,
                    goods_id=goods_id,
                    quantity=quantity
                )
                new_goods.save()
                logging.info('添加成功')
                return Response({
                    'code':1,
                    'message':'添加成功',
                    'data':CartSerializer(new_goods).data
                })

        except Exception as e:
            logging.error(f"商品添加失败:{e}")
            return Response({
                'code':0,
                'message':f"商品添加失败:{e}"
            })



# 查看购物车
class CartDetailView(APIView):

    permission_classes = [IsAuthenticated]

    def get(self,request):
        try:
            user_id = request.user.id
            # 获取该用户所有购物车数据
            cart_goods = Cart.objects.filter(user_id=user_id)

            if not cart_goods:
                logging.error('购物车为空')
                return Response({
                    'code':0,
                    'message':'购物车为空'
                })

            logging.info('获取购物车数据成功')
            return Response({
                'code':1,
                'message':'获取购物车数据成功',
                'data':CartSerializer(cart_goods,many=True).data
            })

        except Exception as e:
            logging.error(f"获取购物车数据失败:{e}")
            return Response({
                'code':0,
                'message':f"获取购物车数据失败:{e}"
            })



# 删除购物车
class CartDeleteView(APIView):

    permission_classes = [IsAuthenticated]
    def post(self,request):
        try:
            user_id = request.user.id
            # 接收参数验证参数
            goods_id = request.data.get('goods_id')
            if not goods_id:
                logging.error('请传递你要删除的课程')
                return Response({
                    'code':0,
                    'message':'请传递你要删除的课程'
                })

            # 判断参数类型
            if isinstance(goods_id,int):
                goods_id = [goods_id]
            if not isinstance(goods_id,list):
                logging.error('参数类型错误')
                return Response({
                    'code':0,
                    'message':'参数类型错误'
                })

            # 判断传过来要删除的id是否在用户的购物车数据中
            delete_count = 0
            for goodId in goods_id:
                if not Cart.objects.filter(user_id=user_id,goods_id=goodId):
                    logging.error('购物车中没有该课程')
                    return Response({
                        'code':0,
                        'message':'购物车中没有该课程'
                    })
                cart_item = Cart.objects.get(user_id=user_id, goods_id=goodId)
                cart_item.delete()
                delete_count += 1   # 删除的数量
            logging.info('删除成功')
            return Response({
                'code':1,
                'message':'删除成功',
                'data':{
                    'delete_count':delete_count
                }
            })

        except Exception as e:
            logging.error(f"删除失败:错误信息为{e}")
            return Response({
                'code':0,
                'message':f"删除失败:错误信息为{e}"
            })




# 全选购物车
class CartAllUpdateView(APIView):

    permission_classes = [IsAuthenticated]
    def post(self,request):

        try:
            user_id = request.user.id
            # 接收参数
            is_selected = int(request.data.get('is_selected'))

            # 判断参数格式
            if is_selected not in [0,1]:
                logging.error('参数格式错误')
                return Response({
                    'code':0,
                    'message':'参数格式错误,必须是0或1'
                })

            if is_selected is None:
                logging.error('请传递你要修改的状态')
                return Response({
                    'code':0,
                    'message':'请传递你要修改的状态'
                })


            # 先获取所有的课程拿到他们的状态：
            cart_goods = Cart.objects.filter(user_id=user_id)

            if not cart_goods:
                logging.error('购物车为空')
                return Response({
                    'code':0,
                    'message':'购物车为空'
                })

            change_count = 0
            for cartGood in cart_goods:
                if cartGood.is_selected != is_selected:
                    cartGood.is_selected = is_selected
                    cartGood.save()
                    change_count += 1

            logging.info(f'修改{change_count}个商品成功')
            return Response({
                'code':1,
                'message':'修改成功',
                'data':CartSerializer(cart_goods,many=True).data
            })


        except Exception as e:
            logging.error(f"修改失败:错误信息为{e}")
            return Response({
                'code':0,
                'message':f"修改失败:错误信息为{e}"
            })





# 反选购物车
class CartNoView(APIView):

    permission_classes = [IsAuthenticated]
    def post(self,request):
        try:
            user_id = request.user.id
            # 接收参数:商品id，因为直接取反
            goods_id = request.data.get('goods_id')
            if not goods_id:
                logging.error('请传递你要反选的课程')
                return Response({
                    'code':0,
                    'message':'请传递你要反选的课程'
                })

            if isinstance(goods_id,int):
                goods_id = [goods_id]
            if not isinstance(goods_id,list):
                logging.error('参数类型错误')
                return Response({
                    'code':0,
                    'message':'参数类型错误'
                })

            # 先获取所有的课程拿到他们的状态：
            cart_goods = Cart.objects.filter(user_id=user_id)
            for cartGood in cart_goods:
                if cartGood.goods_id in goods_id:
                    cartGood.is_selected = not cartGood.is_selected
                    cartGood.save()
            logging.info('修改成功')
            return Response({
                'code':1,
                'message':'修改成功',
                'data':CartSerializer(cart_goods,many=True).data
            })

        except Exception as e:
            logging.error(f"修改失败:错误信息为{e}")
            return Response({
                'code':0,
                'message':f"修改失败:错误信息为{e}"
            })





class LoginView(APIView):
    def post(self,request):
        try:
            username = request.data.get('username')
            password = request.data.get('password')
            if not all ([username,password]):
                logging.error('用户名或密码不能为空')
                return Response({
                    'code':0,
                    'message':'用户名或密码不能为空'
                })

            user = authenticate(username=username,password=password)
            if not user:
                logging.error('用户名或密码错误|用户不存在')
                return Response({
                    'code':0,
                    'message':'用户名或密码错误|用户不存在'
                })

            refresh = RefreshToken.for_user(user)
            logging.info('登录成功')
            return Response({
                'code':1,
                'message':'登录成功',
                'data':{
                    'token':str(refresh.access_token),
                    'user_id':user.id,
                    'username':username,
                    'refresh_token':str(refresh),
                }
            })

        except Exception as e:
            logging.error(f"登录失败:错误信息为{e}")
            return Response({
                'code':0,
                'message':f"登录失败:错误信息为{e}"
            })























